package com.ikkong.common.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import sun.misc.BASE64Decoder;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.jfinal.kit.PropKit;

public class AliyunOSSUtils {
	private static String _aliyunKey = PropKit.get("oss.key");
	private static String _aliyunSecret = PropKit.get("oss.secret");
	private static String endPoint=PropKit.get("oss.endPoint");
	//private static OSSClient ossClient =new OSSClient("http://" + endPoint, _aliyunKey, _aliyunSecret);
	private static String bucketName = PropKit.get("oss.imageBucket");

	public static String putObject(String imgData,String dir) {
		String filePath = null;
		OSSClient ossClient =new OSSClient("http://" + endPoint, _aliyunKey, _aliyunSecret);
		/*if(ossClient==null){
			ossClient=new OSSClient("http://" + endPoint, _aliyunKey, _aliyunSecret);
		}*/

		try {
			String imageData_str = imgData.substring(imgData.indexOf(",") + 1);
			BASE64Decoder decoder = new BASE64Decoder();
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imageData_str);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
		
			String imageData_filename = System.currentTimeMillis() + "";
			String filename_ext = "jpg";
			filePath = dir + imageData_filename + "." + filename_ext;
		/*	if (ossClient.doesBucketExist(bucketName)) {
				System.out.println("您已经创建Bucket：" + bucketName + "。");
			} else {
				ossClient.createBucket(bucketName);
			}*/
			//BucketInfo info = ossClient.getBucketInfo(bucketName);
			InputStream is = new ByteArrayInputStream(bytes);
			PutObjectResult result = ossClient.putObject(bucketName, filePath,is);
			is.close();
			// OSSObject object = ossClient.getObject(new
			// GetObjectRequest(bucketName, firstKey));
			
			filePath="http://"+bucketName+"."+PropKit.get("oss.endPoint")+"/"+filePath;
			// 关闭Client。
		//	ossClient.shutdown();
			
		} catch (OSSException oe) {
			System.out.println(oe.getMessage());
			oe.printStackTrace();
			filePath=null;
		} catch (ClientException ce) {
			System.out.println(ce.getMessage());
			ce.printStackTrace();
			filePath=null;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			filePath=null;
		} finally {
			// 关闭Client

			ossClient.shutdown();
		}
		return filePath;
	}
}
